import axios from "axios";
import store from "../store/main";

const request = axios.create({
  baseURL: "/api",
});

request.interceptors.request.use((request) => {
  store.commit("SETLOADING", true);
  const token = localStorage.getItem("token");
  if (token) {
    request.headers = { ...request.headers, Authorization: "Bearer " + token };
  }
  return request;
});

request.interceptors.response.use(
  (response) => {
    store.commit("SETLOADING", false);
    if (response.status >= 200 && response.status < 300) {
      return response.data;
    } else {
      return Promise.reject(response);
    }
  },
  (err) => {
    store.commit("SETLOADING", false);
    return Promise.reject(err);
  }
);

export default request;
